import { defineStore } from 'pinia'
export const useCartStore = defineStore({
  id: 'cart',
  state: () => {
    return {
      cartList:[],
      select:[]
    }
  },
  getters:{
    checkAll( ){
      return this.cartList.length == this.select.length;
    },
    total(){
      let total = {
        price:0,
        number:0
      }
      this.cartList.forEach(v=>{
        if( this.select.indexOf( v.id ) != -1 ){
          total.price += cartProductPrice * cartProductSale;
          total.number = this.select.length;
        }
      })
      return total;
    },
	getIsAllCheck (state) {
	  // 判断是否全选
	  let isAllCheck = true;
	  for (let i = 0; i < state.cartList.length; i++) {
	    const temp = state.cartList[i];
	    // 只要有一个商品没有勾选立即return false;
	    if (!temp.cartChoose) {
	      isAllCheck = false;
	      return isAllCheck;
	    }
	  }
	  return isAllCheck;
	}
  },
  actions:{
	  unshiftShoppingCart (data) {
	    // 添加购物车
	    // 用于在商品详情页点击添加购物车,后台添加成功后，更新vuex状态
	    this.cartList.unshift(data);
	  },
    //获取数据
    getCartList( list ){
      list.forEach(v=>{
        v['check'] = true;
        this.select.push( v.id );
      })
      this.cartList = list;
    },
	deleteShoppingCart (state, id) {
	  // 根据购物车id删除购物车商品
	  for (let i = 0; i < state.shoppingCart.length; i++) {
	    const temp = state.shoppingCart[i];
	    if (temp.id == id) {
	      state.shoppingCart.splice(i, 1);
	    }
	  }
	},
	// 更新购物车
    updateShoppingCart (state, payload) {
      // 可更新商品数量和是否勾选
      // 用于购物车点击勾选及加减商品数量
      if (payload.prop == "cartSale") {
        // 判断效果的商品数量是否大于限购数量或小于1
        if (state.cartList[payload.key].maxNum < payload.val) {
          return;
        }
        if (payload.val < 1) {
          return;
        }
      }
      // 根据商品在购物车的数组的索引和属性更改
      state.cartList[payload.key][payload.prop] = payload.val;
    },
	
	chooseAll (state, data) {
	
			for (let i = 0; i < state.cartList.length; i++) {
			  state.cartList[i].cartChoose = data;
		}
      // 点击全选按钮，更改每个商品的勾选状态
    
    },
    //单选
    checkItem( index ){
      let id = this.cartList[index].id;
      let idx = this.select.indexOf(id);
      if( idx > -1 ){
          this.cartList[index].check = false;
          this.select.splice(idx,1);
      }else{
          this.cartList[index].check = true;
          this.select.push( id );
      }
    }
  },
})